package net

import (
	"fmt"
	"strconv"
	"strings"
	"syscall"
)

type Socket struct {
	sockFd int
}



func (receiver *Socket) EstablishConnection(host string, port int) {
	sockFd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, syscall.IPPROTO_IP)
	receiver.sockFd = int(sockFd)
	if err != nil {
		fmt.Println("初始化网络连接失败，失败原因：", err.Error())
		if receiver.sockFd > 0 {
			sockOpt := 1

			err := syscall.SetsockoptInt(sockFd, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, sockOpt)
			if err != nil {
				fmt.Println("设置socket关闭模式失败，原因：", err.Error())
			} else {
				syscall.Close(sockFd)
				receiver.sockFd = -1
				return
			}
		}
	}

	inet := syscall.SockaddrInet4{Port: port, Addr: inetAddr(host)}



	if err != nil {
		return
	}

	err = syscall.Connect(sockFd, &inet)
	if err != nil {
		panic("连接错误，错误原因：" + err.Error())
	}
	//TODO：深入理解此处是阻塞io还是非阻塞io，如果是阻塞io，怎么变成非阻塞

}

func (receiver *Socket) SetNonBlockingMode() {
	//todo:设置非阻塞io
}

func (receiver *Socket) CloseConnection() {
	if receiver.sockFd > -1 {
		sockFd := syscall.Handle(receiver.sockFd)
		syscall.Close(sockFd)
		receiver.sockFd = -1
	}
}

func (receiver Socket) IsWriteAble() bool {
	sockFd := syscall.Handle(receiver.sockFd)
	syscall.ConnectEx()

}

func (receiver Socket) IsReadAble() bool {

}

func inetAddr(ipaddr string) [4]byte {
	var (
		ips = strings.Split(ipaddr, ".")
		ip  [4]uint64
		ret [4]byte
	)
	for i := 0; i < 4; i++ {
		ip[i], _ = strconv.ParseUint(ips[i], 10, 8)
	}
	for i := 0; i < 4; i++ {
		ret[i] = byte(ip[i])
	}
	return ret
}

